import router from "../../router";
import store from "../../store";
import utils from "./utils";

router.beforeEach((to, from, next) => {
  if (!window.__POWERED_BY_QIANKUN__ && window.self === window.top) {
    utils.setDocumentTitle(to.meta.title);
  }
  const token = to.query.token || to.query.org_token;
  if (token) {
    store.dispatch("SetToken", token).then(() => {
      delete to.query.token;
      next({
        ...to,
        replace: true,
      });
    });
  } else {
    next();
  }
});

router.afterEach((to, from) => {
  postMessage(to);
});

function postMessage(to) {
  if (!window.__POWERED_BY_QIANKUN__ && window.self !== window.parent) {
    window.parent.postMessage(
      {
        type: "urlChange",
        title: to.meta.title,
        history: JSON.stringify(window.history.state),
        historyLength: window.history.length,
      },
      "*"
    );
  }
}
